<template>
  <a-modal
    title="新增故障模型"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          label="故障级别"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-select style="width: 100%" placeholder="请选择故障级别" v-decorator="['faultLevel', {rules: [{ required: true, message: '请选择故障级别！' }]}]" >
            <a-select-option v-for="(item,i) in faultLevelList" :key="i" :value="item.code" >{{ item.value }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="所属行业"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-select style="width: 100%" placeholder="请选择所属行业" v-decorator="['groupId', {rules: [{ required: true, message: '请选择所属行业！' }]}]" >
            <a-select-option v-for="(item,i) in industryTypeList" :key="i" :value="item.groupId" >{{ item.industryType }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="故障名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input placeholder="请输入故障名称" v-decorator="['faultName', {rules: [{required: true, message: '请输入故障名称！'}]}]" />
        </a-form-item>

        <a-form-item
          label="故障编号"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >
          <a-input placeholder="请输入故障编号" v-decorator="['accessToken', {rules: [{required: true, message: '请输入故障编号！'}]}]" />
        </a-form-item>

        <a-form-item
          label="故障动图"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
          style="text-align: left"
        >
          <a-upload
            name="faultGif"
            :customRequest="customRequest"
            @preview="handlePreview"
            list-type="picture-card"
            :file-list="fileList"
            @change="change"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传文件
              </div>
            </div>
          </a-upload>

        </a-form-item>
        <a-modal :visible="previewVisible" :footer="null" @cancel="previewCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { add } from '@/api/modular/main/bizfaultmodel/bizFaultModelManage'
  import { industryTypeList } from '@/api/modular/main/bizindustryinvolved/bizIndustryInvolvedManage'
  import { getUploadFileName } from '@/api/modular/system/fileManage'
  import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'

  export default {
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        industryTypeList: [],
        modelFile: '',
        faultGif: '',
        faultLevelList: [],
        previewVisible: false,
        previewImage: '',
        fileList: []
      }
    },
    created () {
      this.getFaultLevelList()
      this.getIndustryTypeList()
    },
    methods: {
      add (record) {
        this.visible = true
      },
      getIndustryTypeList () {
        industryTypeList().then(res => {
          this.treeLoading = false
          if (res.success) {
            this.industryTypeList = res.data
          }
        })
      },
      /**
       * 上传文件
       */
      customRequest (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        getUploadFileName(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            switch (data.filename) {
              case 'modelFile':
                this.modelFile = res.data
                break
              case 'faultGif':
                this.faultGif = res.data
                break
            }
            data.onSuccess(res, data.file)
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      getFaultLevelList () {
        sysDictTypeDropDown({ code: 'fault_level' }).then((res) => {
          if (res.success) {
            this.faultLevelList = res.data
          }
        })
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true

        validateFields((errors, values) => {
          if (!errors) {
            values.faultGif = this.faultGif
            add(values).then((res) => {
              this.confirmLoading = false
              if (res.success) {
                this.$message.success('新增成功')
                this.handleCancel()
                this.$emit('ok', values)
              } else {
                this.$message.info('新增失败：' + res.message)
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        this.fileList = []
      },
      getBase64 (file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = () => resolve(reader.result)
          reader.onerror = error => reject(error)
        })
      },
      previewCancel () {
        this.previewVisible = false
      },
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await this.getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      change ({ fileList }) {
        this.fileList = fileList
      }
    }
  }
</script>
